<?php
/**
 * Created by PhpStorm.
 * User: mayn
 * Date: 2018/8/31
 * Time: 13:10
 */

namespace app\common\validate;

use app\lib\exception\ParameterException;
use think\Exception;
use think\Request;
use think\Validate;

class BaseValidate extends Validate
{
    public function goCheck($data = []) {
        // 根据验证场景验证
        if (!is_array($data)) {
            throw new Exception('goCheck的参数必须是数组');
        }

        $params = Request::instance()->param();
        // 判断是否需要根据场景验证
        if (array_key_exists('scene', $data)) {
            $result = $this->scene($data['scene'])->batch()->check($params);
        } else {
            $result = $this->batch()->check($params);
        }

        if (!$result) {
            throw new ParameterException([
                'msg' => $this->error,
                'error_code' => 10000
            ]);
        } else {
            return true;
        }
    }
    public function isPositiveInteger($value) {
        if (is_int($value + 0) && is_numeric($value) && $value + 0 > 0) {
            return true;
        } else {
            return false;
        }
    }
    public function getParameters() {
        $data = Request::instance()->param();
        $newData = [];
        // 如果根据场景验证，获取rule
        if (is_null($this->currentScene)) {
            $rule = $this->rule;
        } else {
            $rule = $this->scene[$this->currentScene];
        }
        // 直接终止程序，防止外部非法修改用户信息
        if (array_key_exists('user_id', $data) || array_key_exists('uid', $data)) {
            throw new ParameterException([
                'msg' => '参数中包含有非法的参数名user_id或者uid'
            ]);
        }
        foreach ($rule as $key => $value) {
            $newData[$key] = $data[$key];
        }
        return $newData;
    }

    public function isNotEmpty($value) {
        if (empty($value)) {
            return false;
        } else {
            return true;
        }
    }

    public function isPhone($value) {
        $phone = trimStr($value);
        if (preg_match('/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/', $phone)) {
            return true;
        } else {
            return false;
        }
    }

    public function isEmail($value) {
        $email = trimStr($value);
        $emailPreg = '/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/';
        if (preg_match($emailPreg, $email)) {
            return true;
        } else {
            return false;
        }
    }

    public function isPassword($value) {
        $password = trimStr($value);
        $passwordPreg = '/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/';
        if (preg_match($passwordPreg, $password)) {
            return true;
        } else {
            return false;
        }
    }
}